import os
import subprocess
import platform

def check_adb_installed(adb_path=None):
    """
    检查ADB是否已安装并配置在系统路径中
    
    Args:
        adb_path (str, optional): ADB可执行文件的路径，如果未指定则使用系统路径中的ADB
        
    Returns:
        tuple: (bool, str) 第一个元素表示ADB是否可用，第二个元素表示ADB路径
    """
    try:
        # 使用指定的ADB路径或系统路径中的ADB
        adb_cmd = [adb_path] if adb_path else ["adb"]
        adb_cmd.append("version")
        
        result = subprocess.run(adb_cmd, capture_output=True, text=True, check=True)
        # 获取实际使用的ADB路径
        if adb_path:
            actual_adb_path = adb_path
        else:
            # 在Windows系统上查找ADB路径
            if platform.system() == "Windows":
                # 尝试从环境变量中查找
                if "ANDROID_HOME" in os.environ:
                    actual_adb_path = os.path.join(os.environ["ANDROID_HOME"], "platform-tools", "adb.exe")
                else:
                    actual_adb_path = "adb"
            else:
                actual_adb_path = "adb"
        
        return True, actual_adb_path
    except (subprocess.SubprocessError, FileNotFoundError):
        return False, adb_path


def get_connected_devices(adb_path=None):
    """
    获取已连接的安卓设备列表
    
    Args:
        adb_path (str, optional): ADB可执行文件的路径
        
    Returns:
        list: 包含已连接设备序列号的列表
    """
    try:
        adb_cmd = [adb_path] if adb_path else ["adb"]
        adb_cmd.extend(["devices"])
        
        result = subprocess.run(adb_cmd, capture_output=True, text=True, check=True)
        # 解析输出，获取设备列表
        devices = []
        for line in result.stdout.splitlines()[1:]:
            if line.strip():
                device_serial = line.split()[0]
                devices.append(device_serial)
        return devices
    except subprocess.SubprocessError as e:
        print(f"获取设备列表失败: {e}")
        return []


def install_apk(apk_path, device_serial=None, adb_path=None):
    """
    使用ADB安装APK到安卓设备
    
    Args:
        apk_path (str): APK文件的路径
        device_serial (str, optional): 设备序列号，如果只有一个设备连接，可以不指定
        adb_path (str, optional): ADB可执行文件的路径
        
    Returns:
        bool: 如果安装成功，返回True；否则返回False
    """
    # 检查APK文件是否存在
    if not os.path.exists(apk_path):
        print(f"APK文件不存在: {apk_path}")
        return False
    
    # 构建ADB安装命令
    adb_cmd = [adb_path] if adb_path else ["adb"]
    if device_serial:
        adb_cmd.extend(["-s", device_serial])
    adb_cmd.extend(["install", "-r", apk_path])
    
    try:
        print(f"开始安装APK: {apk_path}")
        result = subprocess.run(adb_cmd, capture_output=True, text=True, check=True)
        print(f"安装成功: {result.stdout}")
        return True
    except subprocess.SubprocessError as e:
        print(f"安装失败: {e}")
        print(f"错误输出: {e.stderr}")
        return False


def main():
    """
    主函数，演示如何使用上述函数安装APK
    """
    # 检查ADB是否已安装
    adb_available, adb_path = check_adb_installed()
    
    if not adb_available:
        print("ADB未安装或未配置在系统路径中")
        
        # 提供手动指定ADB路径的选项
        manual_adb_path = input("请输入ADB可执行文件的路径 (留空继续): ").strip()

        if not manual_adb_path:
            manual_adb_path = r"E:\project\APK\BleServer.apk"

        
        if manual_adb_path:
            if os.path.exists(manual_adb_path):
                adb_path = manual_adb_path
                adb_available = True
                print(f"使用指定的ADB路径: {adb_path}")
            else:
                print(f"指定的ADB路径不存在: {manual_adb_path}")
                # 提供ADB安装指南
                print("\nADB安装和配置指南:")
                print("1. 下载并安装Android SDK Platform Tools:")
                print("   - Windows: 访问 https://developer.android.com/studio/releases/platform-tools 下载并解压")
                print("   - 将解压后的platform-tools目录添加到系统环境变量PATH中")
                print("2. 或者安装Android Studio，它会自动安装ADB")
                print("3. 安装完成后，重启命令行窗口使环境变量生效")
                return
        else:
            # 提供ADB安装指南
            print("\nADB安装和配置指南:")
            print("1. 下载并安装Android SDK Platform Tools:")
            print("   - Windows: 访问 https://developer.android.com/studio/releases/platform-tools 下载并解压")
            print("   - 将解压后的platform-tools目录添加到系统环境变量PATH中")
            print("2. 或者安装Android Studio，它会自动安装ADB")
            print("3. 安装完成后，重启命令行窗口使环境变量生效")
            return
    
    # 获取已连接的设备
    devices = get_connected_devices(adb_path)
    if not devices:
        print("未检测到已连接的安卓设备")
        print("请确保设备已开启USB调试模式并连接到电脑")
        # 提供设备连接故障排除建议
        print("\n连接故障排除:")
        print("1. 确保USB数据线正常工作")
        print("2. 确保设备已开启USB调试模式 (设置 -> 开发者选项 -> USB调试)")
        print("3. 尝试更换USB端口或重启设备")
        print("4. 对于Windows系统，可能需要安装设备驱动程序")
        return
    
    print("已连接的设备:")
    for i, device in enumerate(devices):
        print(f"{i+1}. {device}")
    
    # 选择设备
    if len(devices) == 1:
        device_serial = devices[0]
        print(f"自动选择唯一设备: {device_serial}")
    else:
        try:
            choice = int(input("请选择要安装的设备编号: ")) - 1
            device_serial = devices[choice]
        except (ValueError, IndexError):
            print("无效的选择")
            return
    
    # 获取APK路径
    apk_path = input("请输入APK文件的路径: ")
    
    # 安装APK
    install_apk(apk_path, device_serial, adb_path)


if __name__ == "__main__":
    main()